package com.xgxf.server.utils;

import com.xgxf.server.pojo.LoginUser;
import com.xgxf.server.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * security 工具类
 */
@Slf4j
@Component
@Configuration
@EnableWebSecurity
public class SecurityUtil extends WebSecurityConfigurerAdapter {

//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        //super.configure(http);
//        //配置不需要登陆验证
//        http.authorizeRequests().anyRequest().permitAll().and().logout().permitAll();
//    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll().and().logout().permitAll().and()
                .formLogin()
                .disable()
                .csrf()
                .disable();;

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
    }

    /**
     * 获取当前登录用户的id
     * @return
     */
    public Integer getUserId()
    {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(ObjectUtils.isEmpty(authentication)){
            log.warn("当前用户未认证或处于测试环境，无法获取用户id");
            return 0;
        }
        LoginUser loginUser = (com.xgxf.server.pojo.LoginUser) authentication.getPrincipal();
        if(ObjectUtils.isEmpty(loginUser))
        {
            log.error("当前用户未登录，无法获取用户id");
            return 0;
        }
        return loginUser.getUser().getId();
    }

    /**
     * 获取当前登录的用户
     * @return
     */
    public User getUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(ObjectUtils.isEmpty(authentication)){
            log.warn("当前用户未认证或处于测试环境，无法获取用户id");
            return null;
        }
        LoginUser loginUser = (com.xgxf.server.pojo.LoginUser) authentication.getPrincipal();
        if(ObjectUtils.isEmpty(loginUser))
        {
            log.error("当前用户未登录，无法获取用户id");
            return null;
        }
        return loginUser.getUser();
    }

}
